package uutalk.netcloud.talk.base.android;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import org.greenrobot.eventbus.EventBus;

import java.lang.ref.WeakReference;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import uutalk.netcloud.talk.R;
import uutalk.netcloud.talk.base.util.ProgressHudUtil;

/**
 * Created by Administrator on 2017/10/23.
 */

public abstract class BaseFragment extends Fragment {

    protected boolean bIsViewCreated;//是否创建了View
    protected boolean bIsDataLoaded;//是否加载了数据

    protected LinearLayout mRootView;//跟目录
    protected String TAG;//标签
    private Unbinder unbinder;
    protected Activity mActivity;
    protected boolean isVisible;

    private ImageView mBackIV;
    private TextView mLeftTV;
    private TextView mTitleTV;
    private TextView mRightTV;

    public ProgressHudUtil progressHudUtil;
    private Handler mHandler;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(mRootView == null){
            setUpView(inflater, setLayoutResId());
        }
        autoBindView();
        bindEvent();

        bIsViewCreated = true;
        return mRootView;
    }



    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mActivity = getActivity();
        progressHudUtil = new ProgressHudUtil(mActivity);
        TAG = getClass().getSimpleName();
        mHandler = new MyHandler(this);
        init();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (isVisibleToUser && bIsViewCreated && !bIsDataLoaded) {
            loadData();
            //bIsDataLoaded = true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        unBindEvent();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        gc();
        bIsDataLoaded = false;
        bIsViewCreated = false;
    }

    public void setUpView(LayoutInflater inflater, @LayoutRes int layoutId) {
        if (layoutId != 0) {
            mRootView = (LinearLayout) inflater.inflate(R.layout.root_layout,
                    null);
            if (supportActionbar()) {
                View toolBarView = inflater.inflate(R.layout.a_fragment_title, null);
                mRootView.addView(toolBarView,new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                        .MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
                setSupportActionBar();
            }
            View contentView = inflater.inflate(layoutId, null);
            mRootView.addView(contentView, new LinearLayout.LayoutParams(ViewGroup.LayoutParams
                    .MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        }
    }



    /**
     * 设置toobar作为导航栏
     */
    public void setSupportActionBar() {
        if (supportActionbar()) {
            mBackIV = (ImageView) mRootView.findViewById(R.id.ivBack);
            mLeftTV = (TextView) mRootView.findViewById(R.id.tvLeft);
            mTitleTV = (TextView) mRootView.findViewById(R.id.tvTitle);
            mRightTV = (TextView) mRootView.findViewById(R.id.tvRight);
            mBackIV.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OnBackPressed(v);
                }
            });
            //mBackIV.setBackground(getResources().getDrawable(R.drawable.hkt_back_32));
            mLeftTV.setVisibility(View.GONE);
            mRightTV.setVisibility(View.GONE);
        }
    }

    public void OnBackPressed(View v) {
        finish();
    }

    public void finish(){
        getActivity().finish();
    }

    public ImageView getBackIV() {
        return mBackIV;
    }

    public TextView getLeftTV() {
        return mLeftTV;
    }

    public TextView getTitleTV() {
        return mTitleTV;
    }

    public TextView getRightTV() {
        return mRightTV;
    }

    /**
     * 是否支持toolbar作为导航栏
     * 如果不需要导航栏 则return false
     *
     * @return
     */
    public boolean supportActionbar() {
        return false;
    }




    public void unBindView() {
        if (isAutoBindView() && unbinder != null) {
            unbinder.unbind();
        }
    }


    public void unBindEvent() {
        if (EventBus.getDefault().isRegistered(this) && isAutoBindEvent()) {
            EventBus.getDefault().unregister(this);
        }
    }

    /**
     * 内存释放等
     */
    public void gc() {
        if (progressHudUtil != null) {
            progressHudUtil.dismissProgressHud();
            progressHudUtil.destory();
        }
        if(mHandler != null){
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
        unBindView();
        mActivity = null;
        unbinder = null;
        mRootView = null;
    }

    protected void autoBindView() {
        if(isAutoBindView()){
            unbinder = ButterKnife.bind(this, mRootView);
        }
    }

    /**
     * 是否绑定事件
     * 默认不绑定
     *
     * @return
     */
    public boolean isAutoBindEvent() {
        return false;
    }


    public void bindEvent() {
        if (isAutoBindEvent()) {
            EventBus.getDefault().register(this);
        }
    }

    protected boolean isAutoBindView(){
        return true;
    }

    /**
     * @return 布局资源id
     */
    protected abstract int setLayoutResId();

    /**
     * 加载数据
     */
    protected abstract void loadData();

    /**
     * 进行初始化操作，与数据加载无关
     */
    protected abstract void init();




    // 返回键按下时会被调用，禁止返回键
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK
                && event.getAction() == KeyEvent.ACTION_DOWN) {
            return true;
        }
        return false;
    }

    public void handleMessage(Message msg) {
    }

    private static final class MyHandler extends Handler {
        private WeakReference<BaseFragment> mBaseFragment;

        public MyHandler(BaseFragment page) {
            mBaseFragment = new WeakReference<>(page);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mBaseFragment != null) {
                BaseFragment page = mBaseFragment.get();
                if (page != null) {
                    page.handleMessage(msg);
                }
            }
        }
    }

    public void sendEmptyMessageToFragment() {
        mHandler.obtainMessage().sendToTarget();
    }

    public void sendMessageToFragment(int what) {
        mHandler.obtainMessage(what).sendToTarget();
    }

    public void sendMessageToFragmentDelay(int what, long delay) {
        mHandler.sendEmptyMessageDelayed(what, delay);
    }

    public void sendMessageToFragment(int what, Object obj) {
        mHandler.obtainMessage(what, obj).sendToTarget();
    }

    public void sendMessageToFragment(int what, int arg1, int arg2) {
        mHandler.obtainMessage(what, arg1, arg2).sendToTarget();
    }

    public void sendMessageToFragment(int what, int arg1, int arg2, Object obj) {
        mHandler.obtainMessage(what, arg1, arg2, obj).sendToTarget();
    }

    public void sendMessageToFragment(Message msg, long delayMillis) {
        mHandler.sendMessageDelayed(msg, delayMillis);
    }


    public void removeMessageFromFragment(int what) {
        mHandler.removeMessages(what);
    }

}
